package com.eci.context.context.filter;

import com.eci.common.asset.constant.StringConstant;
import com.eci.common.asset.kit.JwtUserInfo;
import com.eci.common.util.StringUtils;
import com.eci.context.util.RequestsUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@WebFilter("/**")
@Slf4j
public class EciFilter implements Filter, Ordered {

//    @Autowired
//    Tracer tracer;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        String basePath = req.getRequestURL().toString();
        long startTime = System.currentTimeMillis();
        //缓存tid
//        String tid=tracer.currentSpan().context().traceId();
//        SessionHolder.setTidHolder(StringUtils.isEmpty(tid)?"":tid);
        //保存userIp
        String currentUser = req.getHeader(StringConstant.Authority.AUTH_USER);
        SessionHolder.setUserStr(currentUser);
        SessionHolder.setUserIp(RequestsUtil.getIpAddress(req));
        SessionHolder.setUser(RequestsUtil.getUser(req));
        //初始化mdc
        genMDCInfo(req);
        RequestWrapper requestWrapper = new RequestWrapper(req);
        ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) servletResponse);
        log.info("[{}]收到请求:{}", basePath, requestWrapper.getBodyString() + "|" + requestWrapper.getParaString());
        filterChain.doFilter(requestWrapper, responseWrapper);
        String resultStr = responseWrapper.getResponseData();
        servletResponse.setContentType(responseWrapper.getResponse().getContentType());
        servletResponse.getOutputStream().write(resultStr.getBytes("utf-8"));
        log.info("[{}]返回结果:{}|耗时:[{}ms]", basePath, resultStr, (System.currentTimeMillis() - startTime));
    }

    private void genMDCInfo(HttpServletRequest httpServletRequest) {
        JwtUserInfo user = RequestsUtil.getUser(httpServletRequest);
        MDC.put("userId", user.getAccountId());
    }

    @Override
    public void destroy() {
    }

    @Override
    public int getOrder() {
        return -10000;
    }

}